#
# Copyright (c) 2023 supercell
#
# SPDX-License-Identifier: BSD-3-Clause
#
require "../patterns"

module Luce
  # Parses setext-style headers.
  class SetextHeaderSyntax < BlockSyntax
    def pattern : Regex
      Luce.setext_pattern
    end

    def can_parse?(parser : BlockParser) : Bool
      last_syntax = parser.current_syntax
      return false if parser.setext_heading_disabled? || !last_syntax.is_a?(ParagraphSyntax)
      pattern.matches? parser.current.content
    end

    def parse(parser : BlockParser) : Node?
      lines = parser.lines_to_consume
      return nil if lines.size < 2

      # Remove the last line which is a marker
      lines.pop

      marker = parser.current.content.strip
      level = marker[0] == '=' ? '1' : '2'
      content = lines.map(&.content).join("\n").rstrip
      parser.advance
      Element.new("h#{level}", [UnparsedContent.new(content)] of Node)
    end
  end
end
